package com.clz.workorder.viewmodel

import android.os.Bundle
import android.text.TextUtils
import android.util.TimeUtils
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.config.AppConstants
import com.czl.base.config.OrderType
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.*
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.entity.LocalMedia
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class OrderDetailViewmodel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var op: Double = 0.0
    var isManager = ObservableField<Boolean>(false)
    var isPay = ObservableField<Boolean>(false)
    var isMine = ObservableField<Boolean>(false)
    var subTypeId = ""
    var orderNo = ObservableField<String>("")
    var reportLocation = ObservableField<String>("")
    var reportPersen = ObservableField<String>("")
    var reportPhone = ObservableField<String>("")
    var orderResponsible = ObservableField<String>("")
    var orderMaintain = ObservableField<String>("")
    var orderMaintainPhone = ObservableField<String>("")
    var orderContent = ObservableField<String>("")
    var orderPrice = ObservableField<String>("")
    var orderAttach = ObservableField<ArrayList<LocalMedia>>(ArrayList<LocalMedia>())
    var orderState = ObservableField<String>("")
    var orderStateFlow = ObservableField<ArrayList<ReportOrderState>>()
    var orderButtonText = ObservableField<String>("")
    var managerButtonText = ObservableField<String>("")
    var isSelf=false
    var attachImagesEvent: SingleLiveEvent<ArrayList<LocalMedia>> = SingleLiveEvent()
    var orderStateFlowEvent: SingleLiveEvent<ArrayList<ReportOrderState>> = SingleLiveEvent()
    val cancelOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val deleteOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val onClickManagerButtun: BindingCommand<String> = BindingCommand(BindingAction {
        dealManagerButtun()
    })
    val onClickOrderButtun: BindingCommand<String> = BindingCommand(BindingAction {
        dealOrderButtun()
    })
    val onClickPayText: BindingCommand<Void> = BindingCommand(BindingAction {
        var payInfo = GsonUtils.toJson(
            mapOf(
                "no" to orderNo.get(),
                "payAmount" to orderPrice.get(),
                "areaId" to model.getAreaId()
            )
        )
        startContainerActivity(AppConstants.Router.Pay.F_PAY_DETAIL, Bundle().apply {
            putString(AppConstants.BundleKey.PAY_ORDER_KEY, payInfo)
            putString(AppConstants.BundleKey.WORK_ORDER_IS, AppConstants.Constants.IS_WORK_ORDER)
        })
    })

    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        getData()
    })
    val onRefreshFinishEvent:SingleLiveEvent<Boolean> = SingleLiveEvent()

    fun hasAttach(pl: ArrayList<LocalMedia>): Boolean {
        if (pl == null || pl.size == 0) {
            return false
        }
        return true
    }

    fun getData() {
        model.getOrderDetail(orderNo.get()!!)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<OrderDetailBean>>() {
                override fun onResult(t: BaseBean<OrderDetailBean>) {
                    dismissLoading()
                    if (t.code == 200) {
                        onRefreshFinishEvent.postValue(true)
                        var orderDetail = t.data
                        orderNo.set(orderDetail?.no)
                        reportLocation.set(orderDetail?.location)
                        reportPersen.set(orderDetail?.reporterName)
                        reportPhone.set(orderDetail?.reporterMobile)
                        orderResponsible.set(orderDetail?.handlerName)
                        orderMaintain.set(orderDetail?.repairerName)
                        orderMaintainPhone.set(orderDetail?.repairerMobile)
                        orderContent.set(orderDetail?.description)
                        subTypeId = orderDetail?.subTypeId.toString()
                        var photolist = ArrayList<LocalMedia>()
                        for (item in orderDetail?.files!!) {
                            photolist.add(LocalMedia().apply { path = item
                                mimeType= if (item.endsWith(".mp4")) "video/mp4" else ""})
                        }
                        orderAttach.set(photolist)
                        attachImagesEvent.postValue(photolist)
                        var sls = ArrayList<ReportOrderState>()
                        for (item in orderDetail.operLogs) {
//                            if (isMine.get()==true){
//                                if (TextUtils.equals(item.title,"待接单")
//                                    ||TextUtils.equals(item.title,"已接单")
//                                    ||TextUtils.equals(item.title,"处理完成")
//                                    ||TextUtils.equals(item.title,"已审核")
//                                    ||TextUtils.equals(item.title,"已评价")){
//                                    sls.add(ReportOrderState(item.title,item.score,"",item.memo,formatDateString(item.createTime),"",null))
//                                }
//                            }else{
                            var img = ArrayList<LocalMedia>()
                            if (item.files != null && item.files!!.isNotEmpty()) {
                                for (i in item.files!!) {
                                    img.add(LocalMedia().apply {
                                        path = i
                                        mimeType= if (i.endsWith(".mp4")) "video/mp4" else ""
                                    })
                                }
                            }
                            sls.add(
                                ReportOrderState(
                                    item.title,
                                    item.score,
                                    "",
                                    item.statusDescription,
                                    formatDateString(item.createTime),
                                    item.memo,
                                    img
                                )
                            )
//                            }
                        }
                        op = orderDetail.serviceFee
                        setButten(appenState(sls, orderDetail.status),orderDetail.handlerId)
                        orderStateFlowEvent.postValue(sls)
                    } else {
                        onRefreshFinishEvent.postValue(false)
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    onRefreshFinishEvent.postValue(false)
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun formatDateString(time: String): String {
        if (TextUtils.isEmpty(time)) {
            return ""
        }
        var df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
        var df1 = SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
        var df2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date = df.parse(time)
        var date1 = df1.parse(date.toString())
        var date2 = df2.format(date1)
//        var date3=df2.format(date)
        return date2

    }

    fun appenState(sls: ArrayList<ReportOrderState>, state: Int): String {
        when (state) {
            0 -> {
                return "待接单"
            }
            1 -> {
                sls.add(ReportOrderState("处理中", 0.0, "", "", "", "", null))
                return "处理中"
            }
            2 -> {
                sls.add(ReportOrderState("待审核", 0.0, "", "", "", "", null))
                return "待审核"
            }
            3 -> {
                sls.add(ReportOrderState("待支付", 0.0, "", "", "", "", null))
                return "待支付"
            }
            4 -> {
                sls.add(ReportOrderState("待评价", 0.0, "", "", "", "", null))
                return "待评价"
            }
            5 -> {
                return "已评价"
            }
        }
        return ""
    }

    fun setButten(state: String,handlerId:Int) {
        isSelf = model.getUserId()==handlerId
        if (model.isManager() == -1) {
            if (model.getUserId() == 0) {
                model.getUserDetailInfo().compose(RxThreadHelper.rxSchedulerHelper(this))
                    .subscribe(object : ApiSubscriberHelper<UserInfoBean>() {
                        override fun onResult(t: UserInfoBean) {
                            if (t.code == 200) {
//                                isSelf=t.user.userId==handlerId
                                isSelf=(t.user.userId == handlerId)
                                //问题：换成userId
//                                model.saveUserNickName(t.user.nickName)
                                model.saveUserId(t.user.userId)
                                model.isManager(t.user.userId)
                                    .compose(RxThreadHelper.rxSchedulerHelper(this@OrderDetailViewmodel))
                                    .subscribe(object : ApiSubscriberHelper<BaseBean<Boolean>>() {
                                        override fun onResult(t: BaseBean<Boolean>) {
                                            if (t.code == 200) {
                                                model.saveIsManager(if (t.data == true) 1 else 0)
                                                isManager.set(t.data == true)
                                                setButtenText(state)
                                            } else {
                                                showErrorToast(t.msg)
                                            }
                                        }

                                        override fun onFailed(msg: String?) {
                                            showErrorToast(msg)
                                        }

                                    })
                            } else {
                                showErrorToast(t.msg)
                            }
                        }

                        override fun onFailed(msg: String?) {
                            showErrorToast(msg)
                        }

                    })
            } else {
                model.isManager(model.getUserId())
                    .compose(RxThreadHelper.rxSchedulerHelper(this@OrderDetailViewmodel))
                    .subscribe(object : ApiSubscriberHelper<BaseBean<Boolean>>() {
                        override fun onResult(t: BaseBean<Boolean>) {
                            if (t.code == 200) {
                                model.saveIsManager(if (t.data == true) 1 else 0)
                                isManager.set(t.data == true)
                                setButtenText(state)
                            } else {
                                showErrorToast(t.msg)
                            }
                        }

                        override fun onFailed(msg: String?) {
                            showErrorToast(msg)
                        }

                    })
            }
        } else {
            if (model.isManager() == 1) {
                isManager.set(true)
            } else if (model.isManager() == 0) {
                isManager.set(false)
            }
            setButtenText(state)
        }
    }

    fun setButtenText(state: String) {
        if (isMine.get() == true) {
            setMineOrderButtenText(state)
        } else {
            if (isManager.get() == true) {
                setManageButtenText(state)
            }
            setOtherOrderButtenText(state)
        }
    }

    fun setOtherOrderButtenText(state: String) {
        orderButtonText.set("")
        when (state) {
            "待接单" -> orderButtonText.set("接单")
            "处理中" -> orderButtonText.set("处理完成")
            "待审核" -> {
                setManageButtenText(state)
                if (isSelf) orderButtonText.set("通过") else orderButtonText.set("")
            }

        }
    }

    fun setMineOrderButtenText(state: String) {
        orderButtonText.set("")
        when (state) {
            "待接单" -> orderButtonText.set("撤销")
            "处理中" -> orderButtonText.set("撤销")
            "待支付" -> orderPrice.set(op.toString())
            "待评价" -> orderButtonText.set("评价")
            "已评价" -> orderButtonText.set("删除")
        }
    }

    fun setManageButtenText(state: String) {
        managerButtonText.set("")
        when (state) {
            "待接单" -> managerButtonText.set("转单")
            "处理中" -> managerButtonText.set("转单")
            "待审核" -> {
                if (isSelf) managerButtonText.set("驳回") else managerButtonText.set("")
            }
        }
    }

    fun dealManagerButtun() {
        when (managerButtonText.get()) {
            "转单" -> {
                startContainerActivity(AppConstants.Router.Order.F_TRANSFER_ORDER, Bundle().apply {
                    putString(AppConstants.BundleKey.ORDER_NO_KEY, orderNo.get().toString())
                    putString(AppConstants.BundleKey.REPAIR_TYPE, "5")
                    putString(AppConstants.BundleKey.SUB_TYPE_ID, subTypeId)
                })
            }
            "驳回" -> {
                startContainerActivity(AppConstants.Router.Order.F_RECEIVE_ORDER, Bundle().apply {
                    putString(
                        AppConstants.BundleKey.ORDER_NO_KEY,
                        orderNo.get().toString()
                    )
                    putString(AppConstants.BundleKey.RECEIVE_ORDER_TITLE, "驳回")
                    putString(AppConstants.BundleKey.RECEIVE_ORDER_HINT,"描述驳回意见")
                })
            }
        }
    }

    fun dealOrderButtun() {
        when (orderButtonText.get()) {
            "接单" -> {
                startContainerActivity(AppConstants.Router.Order.F_RECEIVE_ORDER, Bundle().apply {
                    putString(
                        AppConstants.BundleKey.ORDER_NO_KEY,
                        orderNo.get().toString()
                    )
                })
            }
            "处理完成" -> {
                startContainerActivity(AppConstants.Router.Order.F_ORDER_FINISH, Bundle().apply {
                    putString(
                        AppConstants.BundleKey.ORDER_NO_KEY,
                        orderNo.get().toString()
                    )
                    putString(AppConstants.BundleKey.ORDER_RESPONSIBILITY, orderResponsible.get())
                    putString(AppConstants.BundleKey.ORDER_MAINTAIN, orderMaintain.get())
                })
            }
            "通过" -> {
                startContainerActivity(AppConstants.Router.Order.F_RECEIVE_ORDER, Bundle().apply {
                    putString(
                        AppConstants.BundleKey.ORDER_NO_KEY,
                        orderNo.get().toString()
                    )
                    putString(AppConstants.BundleKey.RECEIVE_ORDER_TITLE, "审核通过")
                    putString(AppConstants.BundleKey.RECEIVE_ORDER_HINT,"描述通过意见")
                })
            }
            "撤销" -> {
                cancelOrderEvent.postValue(orderNo.get())
            }
            "支付" -> {}
            "评价" -> {
                startContainerActivity(AppConstants.Router.Report.F_SERVICE_SCORE,
                    Bundle().apply {
                        putString(AppConstants.BundleKey.WORK_ORDER_NO, orderNo.get())
                    })
            }
            "删除" -> {
                deleteOrderEvent.postValue(orderNo.get())
            }

        }
    }

    fun checkOrder() {
        model.checkOrder(CheckOrderRequestBean("", orderNo.get().toString(), 1))
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        LiveBusCenter.postTakeSuccessEvent(OrderType.CHECK_ORDER)
                        showSuccessToast("审核成功！")
                    } else {
                        showSuccessToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun cancelWorkOrder(no: String) {
        model.cancelWorkOrder(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        showSuccessToast("撤销成功！")
                        LiveBusCenter.postTakeSuccessEvent(OrderType.CANCEL_ORDER)
                    } else {
                        showSuccessToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun deleteWorkOrder(no: String) {
        model.deleteWorkOrder(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        showSuccessToast("删除成功！")
                        LiveBusCenter.postTakeSuccessEvent(OrderType.DELETE_ORDER)
                    } else {
                        showSuccessToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }
}